# -*- coding: utf-8 -*-
#
# Copyright (c) 2012, Rafael Pivato
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Rafael Pivato nor the names of its contributors
#       may be used to endorse or promote products derived from this
#       software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL RAFAEL PIVATO BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import json
from urllib import urlencode
from urllib import urlopen


REGION_DOMAIN = {
    'us': 'us.battle.net',
    'eu': 'eu.battle.net',
    'kr': 'kr.battle.net',
    'tw': 'tw.battle.net',
    'cn': 'battlenet.com.cn',
}


default_config = {
    'region': 'us',
    'domain': 'us.battle.net',
    'locale': 'pt_BR',
}


def configure(region, domain=None, locale=None, config=default_config):
    """Defines the region for the community site."""
    if domain is None:
        if region in REGION_DOMAIN:
            domain = REGION_DOMAIN[region]
        else:
            domain = '%s.battle.net' % (region)
    config['region'] = region
    config['domain'] = domain
    config['locale'] = locale


def create_api_uri(path, query=[], config=default_config):
    uri = 'http://%s/api/wow/%s?%s'
    domain = config['domain']
    locale = config['locale']
    if locale is not None:
        query.append(('locale', locale))
    query_string = urlencode(query)
    return uri % (domain, path, query_string)


def download_content(uri):
    try:
        result = urlopen(uri)
        content = result.read()
    except Exception as ex:
        raise BcomaNetworkError(uri, ex)
    else:
        result.close()
        return content


def download_json(uri):
    content = download_content(uri)
    try:
        data = json.loads(content)
    except Exception as ex:
        raise BcomaFormatError(uri, ex)
    else:
        return data


def download_filtered_lines(uri, func):
    result = None
    filtered_objects = []
    try:
        result = urlopen(uri)
        line = result.readline()
        while line:
            filtered = func(line)
            if filtered:
                filtered_objects.append(filtered)
            line = result.readline()
        return filtered_objects
    except Exception as ex:
        raise BcomaNetworkError(uri, ex)
    finally:
        if result:
            result.close()


class BcomaError(Exception):
    """Represents an error related to the Bcoma module.

    Errors will generally be related to network issues.

    """

    def __init__(self, message, inner=None):
        Exception.__init__(self, message, inner)
        self.message = message
        self.inner = inner


class BcomaNetworkError(BcomaError):
    """Represents a network error accessing an URL."""

    def __init__(self, uri, inner=None):
        BcomaError.__init__(self,
            'Network bcoma error downloading content from %s.' % (uri),
            inner=inner)
        self.uri = uri
        self.args = tuple(list(self.args) + [uri])


class BcomaFormatError(BcomaError):
    """Happens when the format of some data fetch is not correct."""

    def __init__(self, uri, inner=None, detail=''):
        BcomaError.__init__(self,
            'Invalid or unrecognized format for bcoma data from %s. %s' % \
            (uri, detail), inner)
        self.uri = uri
        self.detail = detail
        self.args = tuple(list(self.args) + [uri, detail])

from bcoma.character import Character
from bcoma.guild import Guild, Member
from bcoma.auction import Auction, AuctionFile
from bcoma.item import Item, Spell
